package com.bbs.toutiao.controller.client;


import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.service.client.impl.ClientUserHomeServiceImpl;
import com.bbs.toutiao.utils.Result;
import com.bbs.toutiao.vo.article.ArticlePageRequestVo;
import com.bbs.toutiao.vo.client.ArticleUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Map;


/**
 * 描述: 用户主页操作，查询关注
 * 作者： zhangBin
 * 时间： 2024/3/1 22:01
 * 版本： 1.0
 */


@Slf4j
@RestController
@RequestMapping("/api/userHome")
public class ClientUserHomeController {

    @Resource
    ClientUserHomeServiceImpl userHomeService;


    /**
     * 查询用户主页信息
     *
     * @param userId
     * @return Result
     * @author zhangBin
     */
    @GetMapping("/getUserHomeByUserId/{userId}")
    public Result getUserHomeByUserId(@PathVariable int userId, @RequestHeader String token) {
        int userId1;
        ArticleUserVo userVo;
        if (userId <= 0) {
            throw new BaseException(ExceptionEnum.BODY_NOT_MATCH);
        }
        if (StrUtil.isEmpty(token)) {
            userVo = userHomeService.selectUserHome(userId, 0);
        }else{
            try {
                JWT jwt = JWTUtil.parseToken(token);
                userId1 = Integer.parseInt(jwt.getPayload("userId").toString());
                userVo = userHomeService.selectUserHome(userId, userId1);
            } catch (Exception e) {
                throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
            }
        }

        return Result.success("查询成功", userVo);
    }

    /**
     * 查询被关注者的文章信息
     *
     * @param requestVo
     * @return
     */
    @SysLog("查询被关注者的文章信息")
    @PostMapping("/getFollowsArticle")
    public Result getUserHomeByUserId(@RequestBody ArticlePageRequestVo requestVo) {
        if (requestVo.getCreateUserId() < 1 || requestVo.getPage() < 1 || requestVo.getSize() < 1) {
            throw new BaseException(ExceptionEnum.BODY_NOT_MATCH);
        }
        requestVo.setPage(requestVo.getPage(), requestVo.getSize());
        return Result.success("查询成功", userHomeService.selectFollowsArticle(requestVo));
    }


    /**
     * 描述：查询收藏列表，以及收藏总数，通过token解析用户id
     *
     * @param request
     * @return
     */
    @SysLog("用户查询收藏列表")
    @PostMapping("/getCollectList")
    public Result getCollectList(@RequestBody ArticlePageRequestVo pageRequestVo, @RequestHeader String token) {

        try {
            JWT jwt = JWTUtil.parseToken(token);
            int userId = Integer.parseInt(jwt.getPayload("userId").toString());
            pageRequestVo.setCreateUserId(userId);
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        pageRequestVo.setPage(pageRequestVo.getPage(), pageRequestVo.getSize());

        return Result.success("查询成功", userHomeService.selectFavorites(pageRequestVo));
    }

    /**
     * 关注或者取消关注
     *
     * @param userId
     * @param followId
     * @param status
     * @return
     */
    @GetMapping("/follows")
    public Result updateFollows(@PathParam("userId") int userId, @PathParam("followId") int followId, @PathParam("status") int status) {
        if (userId == followId) {
            log.error("用户不能关注自己" + userId + "======" + followId);
            return Result.error(400, "不能关注自己");
        }
        if (userId > 0 && followId > 0) {
            if (userHomeService.addFollows(userId, followId, status) > 0) {
                return Result.success("关注成功");
            }
        }
        return Result.error(404, "数据错误");
    }


    /**
     * 收藏取消收藏
     *
     * @param userId
     * @param followId
     * @param status
     * @return
     */

    @SysLog("用户对文章收藏或取消收藏")
    @GetMapping("/favorites")
    public Result updateFavorites(@PathParam("userId") int userId, @PathParam("articleId") int articleId, @PathParam("status") int status) {
        log.error("用户收藏" + userId + "======" + articleId + "======" + status);
        if (userId > 0 && articleId > 0) {
            int i = userHomeService.addFavorites(userId, articleId, status);
            if (i > 0 && status == 1) {
                return Result.success("收藏成功");
            } else {
                return Result.success("取消收藏");
            }
        }
        return Result.error(404, "数据错误");
    }

    /**
     * 用户查询历史记录
     *
     * @param page
     * @param size
     * @param userId
     * @return
     */
    @GetMapping("/getHistoryList")
    public Result getHistoryList(@PathParam("page") int page, @PathParam("size") int size, @PathParam("userId") int userId) {
        if (userId > 0 && page > 0 && size > 0) {
            page = size * (page - 1);
            return Result.success("查询成功", userHomeService.selectHistory(page, size, userId));
        }
        return Result.error(404, "数据格式错误");
    }

    /**
     * 删除历史记录
     *
     * @param map
     * @param token
     * @return
     */
    @SysLog("用户删除历史记录")
    @PostMapping("/deleteHistory")
    public Result deleteHistory(@RequestBody List<Map<String, Object>> map, @RequestHeader String token) {
        int userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userId = Integer.parseInt(jwt.getPayload("userId").toString());

        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }
        return Result.success("删除成功" + userHomeService.deleteHistory(userId, map) + "条");
    }
}
